package handle

import (
	"path/filepath"

	"github.com/kataras/iris/v12"
	"github.com/kataras/iris/v12/context"
)

type File struct {
}

func (r File) InitRoute(party iris.Party) {
	p := party.Party("/file")
	p.Post("/upload", r.Upload())
	p.Post("/formFiles", r.FormFiles())
	p.Post("/uploadFormFiles", r.UploadFormFiles())
	p.Post("/sendFile", r.SendFile())
}

const maxSize = 8 * iris.MB

func (r File) Upload() iris.Handler {
	return func(ctx *context.Context) {
		// Set a lower memory limit for multipart forms (default is 32 MiB)
		ctx.SetMaxRequestBodySize(maxSize)
		// OR
		// app.Use(iris.LimitRequestBodySize(maxSize))
		// OR
		// OR iris.WithPostMaxMemory(maxSize)

		// single file
		_, fileHeader, err := ctx.FormFile("file")
		if err != nil {
			ctx.StopWithError(iris.StatusBadRequest, err)
			return
		}

		// Upload the file to specific destination.
		dest := filepath.Join("./uploads", fileHeader.Filename)
		ctx.SaveFormFile(fileHeader, dest)
		ctx.Writef("File: %s uploaded!", fileHeader.Filename)
	}
}
func (r File) FormFiles() iris.Handler {
	return func(ctx *context.Context) {
		files, n, err := ctx.FormFiles("files")
		if err != nil {
			ctx.StopWithStatus(iris.StatusInternalServerError)
			return
		}

		ctx.Writef("%d files of %v total size uploaded!", len(files), n)
	}
}
func (r File) UploadFormFiles() iris.Handler {
	return func(ctx *context.Context) {
		files, n, err := ctx.UploadFormFiles("/home/debi/IdeaProjects/GoLearn/web/irisx/handle/")
		if err != nil {
			ctx.StopWithStatus(iris.StatusInternalServerError)
			return
		}

		ctx.Writef("%d files of %d total size uploaded!", len(files), n)
	}
}
func (r File) SendFile() iris.Handler {
	return func(ctx *context.Context) {
		limit := 50.0 * iris.KB
		burst := 100 * iris.KB
		src := "/home/debi/IdeaProjects/GoLearn/web/irisx/handle/files.go"
		// optionally, keep it empty to resolve the filename based on the "src".
		dest := "result.go"
		ctx.SendFileWithRate(src, dest, limit, burst)
	}
}
